/*!
 * \file SynchroNotes.cpp
 * \brief Synchronized Notes, method definitions
 * \author Joao Guerreiro
 * \date  January 13, 2011
 */

#include "SynchroNotes.h"

#define INIT_NOTES 3

/**
 * \brief Constructor of SynchroNotes
 *
 * Retrieves the saved notes from the xml file, if it already exists
 */
SynchroNotes::SynchroNotes() {
    widget.setupUi(this);


    widget.addNoteButton->setToolTip("Add Note");
    widget.deleteNoteButton->setToolTip("Remove Note");

    //setting the font for the initial number of QTextEdit Widgets
    for (int i = 0; i < INIT_NOTES; i++) {

        QTextEdit* textComicSansMS = (QTextEdit*) widget.splitterNotes->widget(i);
        textComicSansMS->setFontFamily("Comic Sans MS");

    }

    connect(widget.addNoteButton, SIGNAL(pressed()), this, SLOT(addNote()));
    connect(widget.deleteNoteButton, SIGNAL(pressed()), this, SLOT(deleteNotes()));

    QString pathToNotes("/home/");

    //get the variable username
    pathToNotes.append(getenv("USER"));
    pathToNotes.append("/Dropbox/SynchroNotes/notes.xml");
    QFile notes(pathToNotes);

    bool fileExists = notes.open(QIODevice::ReadOnly);

    if (fileExists) {

        QXmlStreamReader xml(&notes);

        int i = 0;

        //while not reached end of xml file
        while (!xml.atEnd()) {

            QXmlStreamReader::TokenType token = xml.readNext();

            if (token == QXmlStreamReader::StartDocument) {
                continue;
            }

            if (token == QXmlStreamReader::StartElement) {

                //we extract the notes text from this element
                if (xml.name() == "noteContent") {

                    QTextEdit *text = (QTextEdit*) widget.splitterNotes->widget(i);

                    //in case there are more than INIT_NOTES we need to insert extra widgets
                    if (text == NULL) {
                        QTextEdit* textComicSansMS = new QTextEdit;
                        textComicSansMS->setFontFamily("Comic Sans MS");
                        widget.splitterNotes->insertWidget(widget.splitterNotes->count(), textComicSansMS);
                        text = (QTextEdit*) widget.splitterNotes->widget(widget.splitterNotes->count() - 1);
                    }

                    i++;

                    //copy the text from the xml file onto the appropriate QTextEdit widget
                    text->setText(xml.readElementText());


                }
            }
        }


        xml.clear();

    }

}

/**
 * \brief Destructor of SynchroNotes
 *
 * Only when we exit the application, we save the note's text in the xml file
 */
SynchroNotes::~SynchroNotes() {


    QString pathToNotes("/home/");
    pathToNotes.append(getenv("USER"));
    pathToNotes.append("/Dropbox/SynchroNotes/notes.xml");
    QFile notes(pathToNotes);
    notes.open(QIODevice::WriteOnly | QFile::Truncate);

    QXmlStreamWriter stream(&notes);
    stream.setAutoFormatting(true);
    stream.writeStartDocument();

    //first element
    stream.writeStartElement("SynchroNotes");

    for (int i = 1; i <= widget.splitterNotes->count(); i++) {

        //conversion of int to string
        stringstream ss;
        ss << i;
        string tmp(ss.str());
        QString qs(tmp.c_str());

        QString *note = new QString("note");
        stream.writeStartElement(*note);
        //note number
        stream.writeAttribute("number", qs);

        //write the content of the notes on the xml file
        QTextEdit *noteContent = (QTextEdit*) widget.splitterNotes->widget(i - 1);
        stream.writeTextElement("noteContent", noteContent->toPlainText());
        stream.writeEndElement();


    }

    stream.writeEndElement();
    stream.writeEndDocument();

    //resizing the file after writting on it
    notes.resize(notes.pos());
    notes.close();

}

/**
 * \brief Adding a QTextEdit widget to the QSplitter
 *
 * Adding another text edit zone to the notes in the beginning
 */
void SynchroNotes::addNote() {

    QTextEdit* textComicSansMS = new QTextEdit;
    textComicSansMS->setFontFamily("Comic Sans MS");
    widget.splitterNotes->insertWidget(0, textComicSansMS);

}
/**
 * \brief Deleting QTextEdit widgets from the QSplitter
 *
 * Removing all text edit zones which are empty
 */
void SynchroNotes::deleteNotes() {

    //always leave at least 3 notes on display
    if (widget.splitterNotes->count() > INIT_NOTES) {

        //hide and delete the note at the end
        QTextEdit* text = (QTextEdit*) widget.splitterNotes->widget(widget.splitterNotes->count() - 1);

        for (int i = 0; i < widget.splitterNotes->count(); i++) {

            QTextEdit* text = (QTextEdit*) widget.splitterNotes->widget(i);

            //if the QTextEdit has empty text
            if (text->document()->toPlainText().compare("") == 0) {
                if (widget.splitterNotes->count() - 1 >= INIT_NOTES) {
                    widget.splitterNotes->widget(i)->hide();
                    delete widget.splitterNotes->widget(i);
                    i--;

                }
            }
        }
    }
}